<template>
	<el-dialog class="photoalbum" v-model="dialogVisible" width="705" :before-close="handleClose">
		<template #header>
			<div class="title">
				<h4>网站相册</h4>
				<el-upload :on-change="Pictures" :auto-upload="false" action="#" :show-file-list="false">
					<el-button :loading="loading" size="small" type="danger">上传图片</el-button>
				</el-upload>
				<el-progress v-if="loading" style="flex: 1" :text-inside="true" :show-text="false" :percentage="percentage"></el-progress>
			</div>
		</template>
		<div class="imagebox" v-loading="vloading">
			<div class="terxt">
				<span>共 {{ total }} 张图片</span>
				<span>空间使用: {{ capacity }} KB/10240KB</span>
			</div>
			<div style="flex: 1">
				<el-empty v-if="list.length == 0" description="相册空空,请上传图片" />
				<div class="imgflex">
					<div class="img" v-for="(item, index) in list" :key="index">
						<el-tooltip placement="top">
							<template #content>
								文件大小：{{ Math.floor(item.size / 1024) }}kb
								<br />
								文件类型：{{ item.meta.type }}
								<br />
								文件尺寸：{{ item.meta.width }}px * {{ item.meta.height }}px
								<br />
								上传时间：{{ item.time }}
							</template>
							<div class="flex">
								<el-image :src="'https://webgallery.oss-cn-beijing.aliyuncs.com/' + item.path" @click="emit(item.path)">
									<template #placeholder>
										<div class="image-slot">
											<el-icon>
												<Loading />
											</el-icon>
										</div>
									</template>
									<template #error>
										<div class="image-slot">
											<el-icon>
												<Picture />
											</el-icon>
										</div>
									</template>
								</el-image>
								<el-icon class="close" @click="Delete(item.id)">
									<CircleCloseFilled />
								</el-icon>
							</div>
						</el-tooltip>
					</div>
				</div>
			</div>

			<el-pagination class="pagination" background @current-change="fun" :hide-on-single-page="true" :current-page="curPage" :page-size="pagesize" layout="prev, pager, next" :total="total"></el-pagination>
		</div>
	</el-dialog>
</template>

<script>
	import OSS from 'ali-oss'
	import { dataRequest as api } from '@/api/api'
	export default {
		data() {
			return {
				list: [],
				capacity: 0, //容量KB
				curPage: 1, //当前页
				pagesize: 24, //每页显示数量
				total: 0, //总共多少条
				loading: false,
				vloading: false,
				dialogVisible: true,
				percentage: 0,
			}
		},
		methods: {
			emit(url) {
				this.$emit('send-img', url)
				this.dialogVisible = false
				// 传给父组件  并关闭窗口
			},
			// 删除
			async Delete(id) {
				this.vloading = true
				let array = await api('Delete', 'album', id)
				if (array.code == 200) {
					this.getdata()
					this.$message.success(`删除成功`)
				}
				this.vloading = false
			},
			// 获取数据
			async getdata() {
				this.vloading = true

				let array = await api('Query', 'album', { perPage: this.pagesize, page: this.curPage, offset: 'ASC' })

				if (array.code == 200) {
					this.total = array.data.count / 1
					this.list = array.data.data

					this.capacity = Math.floor(array.data.total / 1024) //计算目前占用多少KB
				}

				this.vloading = false
			},
			// 分页
			fun(page) {
				this.curPage = page
				this.getdata()
			},

			handleClose(done) {
				this.$confirm('确认关闭？')
					.then((_) => {
						done()
					})
					.catch((_) => {})
			},

			async Pictures(ele) {
				let suffix = ele.name.substr(ele.name.lastIndexOf('.')).toLowerCase()
				const allowedExtensions = ['.jpg', '.png', '.jpeg', '.gif']
				// 获取文件名的后缀
				const maxSize = 5 * 1024 * 1024 // 5MB
				// 检查后缀是否在允许的列表中
				if (!allowedExtensions.includes(suffix) || ele.size > maxSize) {
					this.$message.error(`只能上传'.jpg', '.png', '.jpeg', '.gif'后缀的图片文件,且文件小于5M`)
					return
				}

				// 上传文件

				this.loading = true
				let array = await api('Query', 'Coursewareuploadvoucher', { suffix: suffix, size: ele.size })

				if (array.code == 200) {
					let data = array.data
					const ossClient = new OSS({
						region: data.region,
						accessKeyId: data.accessKeyId,
						accessKeySecret: data.accessKeySecret,
						bucket: data.bucket,
						stsToken: data.securityToken,
						endpoint: data.endpoint,
						// 启用自动STS令牌刷新
						refreshSTSToken: true,
					})
					this.percentage = 1
					let datapath = data.path
					ossClient
						.multipartUpload(datapath, ele.raw, {
							progress: async (p, checkpoint) => {
								this.percentage = Math.floor(p * 100) > 0 ? Math.floor(p * 100) : 1
							},
							headers: {
								'Content-Type': 'image/jpg',
								'x-oss-object-acl': 'public-read',
							},
						})
						.then(async (result) => {
							let data = { path: result.name, size: ele.size }

							// 创建一个 FileReader 对象
							const reader = new FileReader()

							// 监听文件加载完成事件
							await new Promise((resolve, reject) => {
								reader.onload = (event) => {
									// 创建一个 Image 对象
									const img = new Image()

									// 设置图片的源
									img.src = event.target.result

									// 图片加载完成后获取宽度和高度
									img.onload = () => {
										const width = img.width // 图片宽度
										const height = img.height // 图片高度
										data.meta = { width: img.width, height: img.height, type: ele.raw.type }
										resolve() // 标记读取完成
									}
								}

								// 监听读取错误事件
								reader.onerror = (error) => {
									reject(error) // 标记读取错误
								}

								// 读取文件内容
								reader.readAsDataURL(ele.raw)
							})

							let array = await api('Create', 'album', data)

							if (array.code == 200) {
								this.percentage = 0
								this.loading = false
								this.curPage = Math.ceil((this.total + 1) / this.pagesize)
								this.getdata()
								this.$message.success(`上传成功`)
							} else {
								this.$message.error(`上传失败`)
							}
						})
						.catch((err) => {
							this.$message.error('因：' + err.message, '上传失败')
							this.loading = false
						})
				} else {
					this.$message.error(array.data)
					this.loading = false
				}
			},
		},
		mounted() {
			this.getdata()
		},
	}
</script>

<style>
	.photoalbum .el-image {
		width: 100px;
		height: 100px;
	}
	.photoalbum .image-slot {
		background: var(--el-fill-color-light);
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 20px;
		width: 100px;
		height: 100px;
	}
	.photoalbum .imgflex {
		display: flex;
		flex-wrap: wrap;
		gap: 15px;
	}
	.photoalbum .img {
		width: 100px;
		height: 100px;
	}

	.photoalbum .el-dialog__body {
		padding: 0px 15px 15px;
	}
</style>
<style scoped>
	.flex:hover .close {
		display: block;
	}
	.flex {
		position: relative;
	}
	.close {
		display: none;
		position: absolute;
		top: 1px;
		right: 1px;
		font-size: 18px;
		color: #f56c6c;
		font-weight: bold;
	}
	.terxt {
		display: flex;
		flex-direction: row;
		gap: 10px;
	}
	.pagination {
		justify-content: center; /* 水平居中 */
	}
	.imagebox {
		height: 539px;
		display: flex;
		flex-direction: column;
		gap: 15px;
	}
	.photoalbum .title {
		display: flex;
		flex-direction: row;
		gap: 10px;
	}
	.dialog-footer button:first-child {
		margin-right: 10px;
	}
</style>
